import os
import sys
from tempfile import mkstemp
from urlparse import urlunparse

from sqlalchemy import create_engine
from dbmigrate.datasource import BaseDataSource


class DataSource(BaseDataSource):
    
    scheme = "sqlite"
    
    show_tables_sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='%(schema_table)s' "
    select_applied_revisions_sql =  "SELECT %(schema_revision_col)s FROM %(schema_table)s"
    insert_revision_sql =  "INSERT INTO %(schema_table)s (%(migration_package_col)s, %(schema_revision_col)s) VALUES (%(package)s, %(revision)s)"
    delete_revision_sql = "DELETE FROM %(schema_table)s WHERE %(schema_revision_col)s = %(revision)s"
    initial_migration = [
   (
"""CREATE TABLE %(schema_table)s (
        %(id_col)s INTEGER PRIMARY KEY AUTOINCREMENT,
        %(migration_package_col)s VARCHAR(128) NOT NULL,
        %(schema_revision_col)s INTEGER UNSIGNED NOT NULL
    )
""",
"""DROP TABLE %(schema_table)s"""
    ),
]

    def __init__(self):
        super(DataSource, self).__init__()
        self.filename = ':memory:'
        self.expansions.update(dict(revision='?', package='?'))        
        self._engine = None
    
    def dbi_placeholder(self):
        return '?'
    
    def read_options(self, options, args):
        self.expansionFromArg(args, 'filename', 0, ':memory:')

    def read_command(self, cmd):
        self.expansionFromCommand(cmd, 'filename', ':memory')
 
    def read_config_file(self, config):
        self.expansionFromIniOption(config, 'filename', ':memory')
 
    def admin_uri(self):
        return urlunparse([self.scheme, '//', self.filename, None, None, None])
    
    app_uri = admin_uri
    migration_uri = admin_uri
    
    def set_up_unit_test(self):
        if self.is_in_memory():
            return
        (fd, self.filename) = mkstemp()
        os.close(fd)
    
    def print_unit_test_information(self):
        if self.is_in_memory():
            print >> sys.stderr, "SQLite database is in memory"
        else:
            print >> sys.stderr, "SQLite database is in the file", self.filename
            
    def tear_down_unit_test(self):
        if self.is_in_memory():
            return
        if os.path.exists(self.filename):
            os.unlink(self.filename)
            
    def is_in_memory(self):
        return self.filename == ':memory:'
    
    filename = property(lambda self: self.expansions.__getitem__('filename'),
                        lambda self, v: self.expansions.__setitem__('filename', v))

    def create_database(self):
        pass
    
    def drop_database(self):
        pass
    

    
    
